package com.purchase.service.impl;

import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;

import com.purchase.service.CouponService;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import com.alibaba.fastjson.JSONObject;
import com.purchase.entity.AppUser;
//import com.purchase.entity.Employe;
import com.purchase.entity.UserSession;
import com.purchase.entity.WxUser;
import com.purchase.mapper.AppUserMapper;
//import com.purchase.mapper.EmployeMapper;
import com.purchase.mapper.UserSessionMapper;
import com.purchase.mapper.WxUserMapper;
import com.purchase.service.IUserAccessService;
import com.purchase.util.JavaWebToken;
import com.purchase.util.LogInfo;
import com.purchase.util.MD5FileUtil;
import com.purchase.util.RequestForm;
import com.purchase.util.ResponseForm;
import com.purchase.util.WxUserAccessUtil;

import lombok.extern.slf4j.Slf4j;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;

/**
 * @ClassName: UserAccessServiceImpl.java
 * @Module: 	用户访问接口实现类
 * @Description: 实现微信账号访问接口
 * 
 * @author: liuhoujie
 * @date: 2017年12月13日 下午5:35:53
 * 
 */
@Slf4j
@Service
public class UserAccessServiceImpl implements IUserAccessService {
	@Resource
	WxUserMapper wxUserMapper;
	@Resource
	UserSessionMapper userSessionMapper;
	@Autowired
	private CouponService couponService;
	@Autowired
	AppUserMapper appUserMapper;
	
	@Transactional
	@SuppressWarnings("unchecked")
	@Override
	public ResponseForm wechatUserlogin(RequestForm requestForm) {
		ResponseForm result = new ResponseForm();
		Map<String,Object> paramMap = (Map<String,Object>)requestForm.getData();
		try {
			String code = paramMap.get("wxCode").toString();
			String storeNo = paramMap.get("storeNo").toString();
			//使用登录凭证 code获取openid和session_key
			JSONObject wxLoginInfo = WxUserAccessUtil.getSessionKeyOropenid(code,storeNo);
			String sessionKey = wxLoginInfo.getString("session_key");
			String openId = wxLoginInfo.getString("openid");
			//保存微信用户登录态，返回自有accessToken
			String sessionId = keepSession(openId,sessionKey);
			
			//wxCode只能用一次，用第二次的时候openId和sessionId为null值，提示
			if(null ==openId || null==sessionId)
			{
				result.setStatus(false);
				result.setCode("400");
				result.setMessage("PARAM_UNKNOWN");
				result.setTotal(0);
				return result;
			}
			//此逻辑应基于redis缓存实现
			//根据openid判断用户是否已存在，若不存在则创建用户，保存wxUid，wxSid，openId，sessionKey
			//若存在则返回wxUid。
			WxUser queryMap = new WxUser();
			queryMap.setOpenId(openId);
			WxUser user = wxUserMapper.selectOne(queryMap);
			String wxUid = "";
			if(user!=null )
			{
				if(null!=user.getWxUid())
					wxUid=user.getWxUid();//该用户已存在
			}
			if(StringUtils.isBlank(wxUid))
			{
				Date date = new Date();
				Timestamp timeStamp = new Timestamp(date.getTime());
				wxUid = UUID.randomUUID().toString();//分配用户ID
				WxUser newUser = new WxUser();
				newUser.setWxUid(wxUid);
				newUser.setOpenId(openId);
				newUser.setSessionKey(sessionKey);
				newUser.setCreateTime(timeStamp);
				wxUserMapper.insertSelective(newUser);//创建新用户
			}
			Map<String,String> userSessionInfo = new HashMap<String,String>();
			userSessionInfo.put("wxUid", wxUid);
			userSessionInfo.put("wxSid", sessionId);
			result.setData(userSessionInfo);
			result.setCode("200");
			result.setMessage("SID_VALID");
			result.setTotal(0);
			return result;
		}catch (Exception e) {
			result.setStatus(false);
			result.setMessage("用户登录错误");
			log.error(e + "用户登录错误");
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); 
			e.printStackTrace();
		}
		return result;
	}
	
	
	@Transactional
	@SuppressWarnings({ "unused", "rawtypes" })
	@Override
	public ResponseForm authorize(RequestForm param) {
		ResponseForm result = new ResponseForm();
		if (param.getData() != null) {
			Map paramMap = (Map) param.getData();
			String storeNo = (String)paramMap.get("storeNo");
			String wxCode =(String)paramMap.get("wxCode");
			String encryptedData = (String)paramMap.get("encryptedData");
			String signature = (String)paramMap.get("signature");
			String iv = (String)paramMap.get("iv");
			String inviteCode = (String)paramMap.get("inviteCode");
			/*检查参数*/
			if (StringUtils.isBlank(wxCode) || StringUtils.isBlank(iv) || StringUtils.isBlank(encryptedData)
					|| StringUtils.isBlank(signature)) {
				result.fail("400", "缺少必要参数");
				return result;
			}
			/*获取openId 和 sessionKey*/
			JSONObject wxLoginInfo = WxUserAccessUtil.getSessionKeyOropenid(wxCode,storeNo);
			String sessionKey = wxLoginInfo.getString("session_key");
			String openId = wxLoginInfo.getString("openid");
			if(wxLoginInfo==null||StringUtils.isBlank(openId)||StringUtils.isBlank(sessionKey)) {
				result.fail("400", "登录已过期");
				return result;
			}
			/*解密用户信息*/
			String userInfo = WxUserAccessUtil.getUserInfoStr(encryptedData, sessionKey, iv);
			WxUser wxUserInfo = JSONObject.parseObject(userInfo, WxUser.class);
			if(userInfo==null||StringUtils.isBlank(wxUserInfo.getUnionId())) {
				result.fail("400", "登录已过期");
				return result;
			}
			String unionId = wxUserInfo.getUnionId();
			try {
				/* openId和sessionKey处理,保存 */
				String wxSid = keepSession(openId, sessionKey);
				/*根据openId检查wxUser否存在,若不存在说明是新用户*/
				WxUser wxUser = new WxUser();
				wxUser.setOpenId(openId);
				wxUser = wxUserMapper.selectOne(wxUser);
				/*根据unionId检查appUser否存在,存在说明已使用过App,身份和推荐人都要携带*/
				AppUser appUser = new AppUser();
				appUser.setUnionId(unionId);
				appUser = appUserMapper.selectOne(appUser);
				String wxUid = null;
				Integer userStatus = null;
				if (wxUser == null) {/* 新用户 */
					if (appUser == null) {
						/*没使用过app,创建wxUid,普通用户*/
						wxUid = UUID.randomUUID().toString();
						userStatus = 0;
					}else {
						/*已使用过app,获取wxUid ,携带app身份(普通用户身分不携带), 推荐人code*/
						wxUid = appUser.getWxUid();
						userStatus = appUser.getUserStatus()>0?appUser.getUserStatus():0;
						inviteCode = StringUtils.isNotBlank(appUser.getParentInviteCode())?appUser.getParentInviteCode():inviteCode;
					}
					wxUserInfo.setWxUid(wxUid);
					wxUserInfo.setUserStatus(userStatus);
					if (StringUtils.isNotBlank(inviteCode))
						wxUserInfo.setInviteCode(inviteCode);
					log.info("=============================新增用户==================================");
					wxUserMapper.insertSelective(wxUserInfo);
					
					//新用户绑定新人优惠券
					couponService.bindNewUserCoupons(wxUid,"JSAPI");
				}else {/* 已存在用户 更新用户信息 */
					if (appUser != null) {
						/*使用过app,携带用户身份(如果身份不是普通用户)*/
						userStatus = appUser.getUserStatus()>0?appUser.getUserStatus():userStatus;
						inviteCode = StringUtils.isNotBlank(appUser.getParentInviteCode())?appUser.getParentInviteCode():inviteCode;
						if(StringUtils.isBlank(wxUser.getInviteCode())) {/*判断wxUser的inviteCode是否为空*/
							wxUserInfo.setInviteCode(inviteCode);
						}else {
							wxUserInfo.setInviteCode(appUser.getInviteCode());
						}
					}else{
						wxUserInfo.setInviteCode(StringUtils.isNotBlank(wxUser.getInviteCode())?null:inviteCode);
					}
					wxUserInfo.setUserStatus(userStatus);
					wxUserInfo.setUserId(wxUser.getUserId());
					wxUserMapper.updateByPrimaryKeySelective(wxUserInfo);
					log.info("=============================更新用户==================================");
				}
				Integer userId = wxUserInfo.getUserId();
				WxUser wxUserResult = wxUserMapper.selectByPrimaryKey(userId);
				Map<String, Object> loginInfo = new HashMap<>();
				loginInfo.put("userId", userId);
				String sessionId = JavaWebToken.createJavaWebToken(loginInfo);
				wxUserResult.setSessionId(sessionId);
				wxUserResult.setWxSid(wxSid);
				result.succ("授权成功", wxUserResult);
			} catch (Exception e) {
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
				result.fail("400", "请求失败");
				e.printStackTrace();
			}
		}else {
			result.fail("400", "参数为空");
		}
		return result;
	}
	
	@Transactional
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Override
	public ResponseForm authorize2(RequestForm requestForm) {
		ResponseForm result = new ResponseForm();
		Map<String,Object> paramMap = (Map<String,Object>)requestForm.getData();
		try {
			String code = paramMap.get("wxCode").toString();
			String storeNo = paramMap.get("storeNo").toString();
			//使用登录凭证 code获取openid和session_key
			JSONObject wxLoginInfo = WxUserAccessUtil.getSessionKeyOropenid(code,storeNo);
			String sessionKey = wxLoginInfo.getString("session_key");
			String openId = wxLoginInfo.getString("openid");
			//保存微信用户登录态，返回自有accessToken
			String sessionId = keepSession(openId,sessionKey);
			
			//推广码(推广人手机号)
			String inviteCode = (String) paramMap.get("inviteCode");
			
			//userId
			Integer userId = null;
			
			Integer userStatus = null;
			
			//verifyPhone 绑定手机号
			String verifyPhone = "";
			//wxCode只能用一次，用第二次的时候openId和sessionId为null值，提示
			if(null ==openId || null==sessionId)
			{
				result.setStatus(false);
				result.setCode("400");
				result.setMessage("wxCode已失效,请重新获取!");
				result.setTotal(0);
				return result;
			}
			//此逻辑应基于redis缓存实现
			//根据openid判断用户是否已存在，若不存在则创建用户，保存wxUid，wxSid，openId，sessionKey
			//若存在则返回wxUid。
			WxUser user = new WxUser();
			user.setOpenId(openId);
			user = wxUserMapper.selectOne(user);
//			if(user!=null )
//			{
//				if(null!=user.getWxUid())
//					wxUid=user.getWxUid();//该用户已存在
//			}
			String wxUid = "";
			if(user==null)//user为空说明为新用户,创建wxUid并保存推广码信息
			{
				Date date = new Date();
				Timestamp timeStamp = new Timestamp(date.getTime());
				wxUid = UUID.randomUUID().toString();//分配用户ID
				WxUser newUser = new WxUser();
				newUser.setWxUid(wxUid);
				newUser.setOpenId(openId);
				newUser.setSessionKey(sessionKey);
				newUser.setCreateTime(timeStamp);
				if (StringUtils.isNotBlank(inviteCode)) {
					newUser.setInviteCode(inviteCode);
				}
				newUser.setUserStatus(0);
				wxUserMapper.insertSelective(newUser);//创建新用户
				userId = newUser.getUserId();
				userStatus = newUser.getUserStatus();

				//新用户绑定新人优惠券
				couponService.bindNewUserCoupons(wxUid,"JSAPI");
			}else {
				wxUid = user.getWxUid();
				userId = user.getUserId();
				verifyPhone=user.getVerifyPhone();
				if(StringUtils.isBlank(user.getInviteCode())&&StringUtils.isNotBlank(inviteCode)) {
					user.setInviteCode(inviteCode);
					wxUserMapper.updateByPrimaryKeySelective(user);
				}
				userStatus=user.getUserStatus();
			}
			Map userSessionInfo = new HashMap<>();
			userSessionInfo.put("wxUid", wxUid);
			userSessionInfo.put("wxSid", sessionId);
			userSessionInfo.put("verifyPhone", verifyPhone);
			userSessionInfo.put("userStatus", userStatus);
			
			Map<String, Object> loginInfo = new HashMap<>();
			loginInfo.put("userId", userId);
			userSessionInfo.put("sessionId", JavaWebToken.createJavaWebToken(loginInfo));
			
			result.setData(userSessionInfo);
			result.setCode("200");
			result.setStatus(true);
			result.setMessage("SID_VALID");
			result.setTotal(0);
			return result;
		}catch (Exception e) {
			result.setStatus(false);
			result.setCode("500");
			result.setMessage("用户登录错误");
			log.error(e + "用户登录错误");
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); 
			e.printStackTrace();
		}
		return result;
	}
	
    /**
     * 微信小程序用户登录态维护
     * @param openId		微信用户唯一标识
     * @param sessionKey	会话秘钥
     * @return	sessionId	应用服务分配的sessionId
     */
	@Transactional
	public String keepSession(String openId, String sessionKey) {
		//计算sessionId
		StringBuffer sb = new StringBuffer();
		sb.append(openId).append(sessionKey);
		String sessionId = MD5FileUtil.getMD5String(sb.toString());
		
		//判断session是否过期，若过期则重新生成，否则返回原来的sessionId;
		//如果过期微信接口返回的sessionKey值不一样，自有生成的sessionId也不一样
		UserSession paramMap = new UserSession();
//		paramMap.setSessionId(sessionId);
//		int count = userSessionMapper.selectCount(paramMap);
//		if(count==0)
//		{
//			Date date = new Date();
//			UserSession session = new UserSession();
//			session.setSessionId(sessionId);
//			session.setOpenId(openId);
//			session.setSessionKey(sessionKey);
//			session.setCreateTime(date.getTime());
//			userSessionMapper.insert(session);
//		}
		paramMap.setOpenId(openId);
		paramMap = userSessionMapper.selectOne(paramMap);
		UserSession session = new UserSession();
		Date date = new Date();
		if(paramMap==null)
		{	/*如果没有session添加*/
			System.err.println("=======================SESSION=================INSERT=======================");
			session.setSessionId(sessionId);
			session.setOpenId(openId);
			session.setSessionKey(sessionKey);
			session.setCreateTime(date.getTime());
			userSessionMapper.insertSelective(session);
		}
		else{
			/*如果获取到session 更新session*/
			System.err.println("========================SESSION=================UPDATE========================");
			session.setId(paramMap.getId());
			session.setSessionId(sessionId);
			session.setOpenId(openId);
			session.setSessionKey(sessionKey);
			session.setCreateTime(date.getTime());
			userSessionMapper.updateByPrimaryKeySelective(session);
		}
		return sessionId;
	}

	@Transactional
	@SuppressWarnings("unchecked")
	public ResponseForm saveUserInfo(RequestForm requestForm) {
		ResponseForm result = new ResponseForm();
		result.setStatus(false);
		result.setCode("400");
		result.setMessage("PARAM_UNKNOWN");
		result.setTotal(0);
		Map<String,Object> paramMap = (Map<String,Object>)requestForm.getData();
		try {
			String wxUid = paramMap.get("wxUid").toString();
			String sessionId = paramMap.get("wxSid").toString();
			String encryptedData = paramMap.get("encryptedData").toString();
			if(StringUtils.isBlank(encryptedData)) {
				return result;
			}
			String signature = paramMap.get("signature").toString();
			String iv = paramMap.get("iv").toString();
			
			//---此逻辑修改为从redis中获取sessionKey
			UserSession queryMap = new UserSession();
			queryMap.setSessionId(sessionId);
			Map<String,String> map = new HashMap<String,String>();
			map.put("session_id", sessionId);
			UserSession session = userSessionMapper.getUserSessionBySid(sessionId);
			if(null ==session)
			{
				return result;
			}
			String sessionKey = session.getSessionKey();
			//解密用户信息
			JSONObject userInfo = WxUserAccessUtil.getUserInfo(encryptedData, sessionKey, iv);
			if(null ==userInfo)
			{
				result.setStatus(false);
				result.setCode("400");
				result.setMessage("SESSION_EXPIRED");
				result.setTotal(0);
				return result;
			}
			String city = userInfo.getString("city");
			String country = userInfo.getString("country");
			String gender =  userInfo.getString("gender");
			String headImage = userInfo.getString("avatarUrl");
			String language = userInfo.getString("language");
			String nickName = userInfo.getString("nickName");
			String province = userInfo.getString("province");
			String unionId = userInfo.getString("unionId");
			if(StringUtils.isBlank(nickName)) {
				{
					result.setStatus(false);
					result.setCode("400");
					result.setMessage("SESSION_EXPIRED");
					result.setTotal(0);
					return result;
				}
			}
			nickName = new String(nickName.getBytes(), "UTF-8");
//			String mobile = userInfo.getString("");
			Date date = new Date();
			Timestamp timeStamp = new Timestamp(date.getTime());
			
			//更新微信用户信息:更新用户表
			WxUser user = new WxUser();
			user.setWxUid(wxUid);
			user.setCity(city);
			user.setCountry(country);
			user.setGender(gender);
			user.setHeadImage(headImage);
			user.setLanguage(language);
			user.setNickName(nickName);
			user.setProvince(province);
			user.setLatestOnlinetime(timeStamp);
			if(null!=unionId)
				user.setUnionId(unionId);
			user.setSessionKey(sessionKey);
//			user.setMobile(mobile);
			System.err.println("=======================用户信息=============UPDATE================");
			Example example = new Example(WxUser.class);
			Criteria criteria=example.createCriteria();
			criteria.andEqualTo("wxUid", wxUid);
			int r = wxUserMapper.updateByExampleSelective(user, example);
			if(r==0 && null!=wxUid) {
				System.err.println("======================用户信息========INSERT==========================");
				wxUserMapper.insertSelective(user);
			}
			Map<String,String> userSessionInfo = new HashMap<String,String>();
			userSessionInfo.put("wxUid", wxUid);
			userSessionInfo.put("wxSid", sessionId);
			result.setData(userSessionInfo);
			result.setCode("200");
			result.setStatus(true);
			result.setMessage("SID_VALID");
			result.setTotal(1);
			return result;
		}catch (Exception e) {
			e.printStackTrace();
			result.setStatus(false);
			result.setMessage("用户登录错误");
			log.error(e + "用户登录错误");
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); 
		}
		return result;
	}
	
	@Transactional
	@SuppressWarnings("unchecked")
	public ResponseForm newSaveUserInfo(RequestForm requestForm) {
		ResponseForm result = new ResponseForm();
		result.setStatus(false);
		result.setCode("400");
		result.setMessage("保存信息失败,请重试!");
		result.setTotal(0);
		Map<String,Object> paramMap = (Map<String,Object>)requestForm.getData();
		try {
			String wxUid = paramMap.get("wxUid").toString();
			String sessionId = paramMap.get("wxSid").toString();
			String encryptedData = paramMap.get("encryptedData").toString();
			String verifyPhone = (String) paramMap.get("verifyPhone");
			if(StringUtils.isBlank(encryptedData)) {
				return result;
			}
			String signature = paramMap.get("signature").toString();
			String iv = paramMap.get("iv").toString();
			
			//---此逻辑修改为从redis中获取sessionKey
			UserSession queryMap = new UserSession();
			queryMap.setSessionId(sessionId);
			Map<String,String> map = new HashMap<String,String>();
			map.put("session_id", sessionId);
			UserSession session = userSessionMapper.getUserSessionBySid(sessionId);
			if(null ==session)
			{
				return result;
			}
			String sessionKey = session.getSessionKey();
			//解密用户信息
			JSONObject userInfo = WxUserAccessUtil.getUserInfo(encryptedData, sessionKey, iv);
			if(null ==userInfo)
			{
				result.setStatus(false);
				result.setCode("400");
				result.setMessage("登录已过期,请重试!");
				log.error("SESSION_EXPIRED");
				result.setTotal(0);
				return result;
			}
			String city = userInfo.getString("city");
			String country = userInfo.getString("country");
			String gender =  userInfo.getString("gender");
			String headImage = userInfo.getString("avatarUrl");
			String language = userInfo.getString("language");
			String nickName = userInfo.getString("nickName");
			String province = userInfo.getString("province");
			String unionId = userInfo.getString("unionId");
			if(StringUtils.isBlank(nickName)) {
				{
					result.setStatus(false);
					result.setCode("400");
					result.setMessage("登录已过期,请重试!");
					log.error("SESSION_EXPIRED");
					result.setTotal(0);
					return result;
				}
			}
			nickName = new String(nickName.getBytes(), "UTF-8");
//			String mobile = userInfo.getString("");
			Date date = new Date();
			Timestamp timeStamp = new Timestamp(date.getTime());
			
			//更新微信用户信息:更新用户表
			WxUser user = new WxUser();
			user.setWxUid(wxUid);
			user.setCity(city);
			user.setCountry(country);
			user.setGender(gender);
			user.setHeadImage(headImage);
			user.setLanguage(language);
			user.setNickName(nickName);
			user.setProvince(province);
			user.setLatestOnlinetime(timeStamp);
			if(null!=unionId)
				user.setUnionId(unionId);
			user.setSessionKey(sessionKey);
//			user.setMobile(mobile);
			System.err.println("=======================用户信息=============UPDATE================");
			Example example = new Example(WxUser.class);
			Criteria criteria=example.createCriteria();
			criteria.andEqualTo("wxUid", wxUid);
			criteria.andEqualTo("verifyPhone", verifyPhone);
			int r = wxUserMapper.updateByExampleSelective(user, example);
			if(r==0 && null!=wxUid) {
				result.setCode("400");
				result.setStatus(false);
				result.setMessage(LogInfo.PARAM_ERROR);
				return result;
			}
			Map<String,String> userSessionInfo = new HashMap<String,String>();
			userSessionInfo.put("wxUid", wxUid);
			userSessionInfo.put("wxSid", sessionId);
			result.setData(userSessionInfo);
			result.setCode("200");
			result.setStatus(true);
			result.setMessage("SID_VALID");
			result.setTotal(1);
			return result;
		}catch (Exception e) {
			e.printStackTrace();
			result.setStatus(false);
			result.setMessage("登录错误");
			log.error(e + "登录错误");
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); 
		}
		return result;
	}
	
	@Transactional
	@SuppressWarnings("unchecked")
	public ResponseForm saveUserInfo2(RequestForm requestForm) {
		ResponseForm result = new ResponseForm();
		result.setStatus(false);
		result.setCode("400");
		result.setMessage("保存信息失败,请重试!");
		result.setTotal(0);
		Map<String,Object> paramMap = (Map<String,Object>)requestForm.getData();
		try {
			String wxUid = paramMap.get("wxUid").toString();
			String sessionId = paramMap.get("wxSid").toString();
			String encryptedData = paramMap.get("encryptedData").toString();
//			String verifyPhone = (String) paramMap.get("verifyPhone");
			if(StringUtils.isBlank(encryptedData)) {
				return result;
			}
			String signature = paramMap.get("signature").toString();
			String iv = paramMap.get("iv").toString();
			
			//---此逻辑修改为从redis中获取sessionKey
			UserSession queryMap = new UserSession();
			queryMap.setSessionId(sessionId);
			Map<String,String> map = new HashMap<String,String>();
			map.put("session_id", sessionId);
			UserSession session = userSessionMapper.getUserSessionBySid(sessionId);
			if(null ==session)
			{
				return result;
			}
			String sessionKey = session.getSessionKey();
			//解密用户信息
			JSONObject userInfo = WxUserAccessUtil.getUserInfo(encryptedData, sessionKey, iv);
			if(null ==userInfo)
			{
				result.setStatus(false);
				result.setCode("400");
				result.setMessage("登录已过期,请重试!");
				log.error("SESSION_EXPIRED");
				result.setTotal(0);
				return result;
			}
			String city = userInfo.getString("city");
			String country = userInfo.getString("country");
			String gender =  userInfo.getString("gender");
			String headImage = userInfo.getString("avatarUrl");
			String language = userInfo.getString("language");
			String nickName = userInfo.getString("nickName");
			String province = userInfo.getString("province");
			String unionId = userInfo.getString("unionId");
			if(StringUtils.isBlank(nickName)) {
				{
					result.setStatus(false);
					result.setCode("400");
					result.setMessage("登录已过期,请重试!");
					log.error("SESSION_EXPIRED");
					result.setTotal(0);
					return result;
				}
			}
			nickName = new String(nickName.getBytes(), "UTF-8");
//			String mobile = userInfo.getString("");
			Date date = new Date();
			Timestamp timeStamp = new Timestamp(date.getTime());
			
			//更新微信用户信息:更新用户表
			WxUser user = new WxUser();
			user.setWxUid(wxUid);
			user.setCity(city);
			user.setCountry(country);
			user.setGender(gender);
			user.setHeadImage(headImage);
			user.setLanguage(language);
			user.setNickName(nickName);
			user.setProvince(province);
			user.setLatestOnlinetime(timeStamp);
			if(null!=unionId)
				user.setUnionId(unionId);
			user.setSessionKey(sessionKey);
//			user.setMobile(mobile);
			System.err.println("=======================用户信息=============UPDATE================");
			Example example = new Example(WxUser.class);
			Criteria criteria=example.createCriteria();
			criteria.andEqualTo("wxUid", wxUid);
//			criteria.andEqualTo("verifyPhone", verifyPhone);
			int r = wxUserMapper.updateByExampleSelective(user, example);
			if(r==0) {
				result.setCode("400");
				result.setStatus(false);
				result.setMessage("用户信息保存失败!");
				return result;
			}
			Map<String,String> userSessionInfo = new HashMap<>();
			userSessionInfo.put("wxUid", wxUid);
			userSessionInfo.put("wxSid", sessionId);
			result.setData(userSessionInfo);
			result.setCode("200");
			result.setStatus(true);
			result.setMessage("SID_VALID");
			result.setTotal(1);
			return result;
		}catch (Exception e) {
			e.printStackTrace();
			result.setCode("500");
			result.setStatus(false);
			result.setMessage("登录错误");
			log.error(e + "登录错误");
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); 
		}
		return result;
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public ResponseForm getUserRole(RequestForm requestForm) {
		ResponseForm result = new ResponseForm();
		Map<String,Object> paramMap = (Map<String,Object>)requestForm.getData();
		try {
			String storeNo = paramMap.get("storeNo").toString();
			String wxUid = paramMap.get("wxUid").toString();
			String sessionId = paramMap.get("wxSid").toString();
			
			//从员表中查找
			int r = wxUserMapper.getUserRole(storeNo, wxUid);
			String roleId = r>0?"1":"0";
			Map<String,String> userSessionInfo = new HashMap<String,String>();
			userSessionInfo.put("wxUid", wxUid);
			userSessionInfo.put("wxSid", sessionId);
			userSessionInfo.put("storeNo", storeNo);
			userSessionInfo.put("roleId", roleId);
			result.setData(userSessionInfo);
			result.setCode("200");
			result.setMessage("ROLE_VALID");
			result.setTotal(1);
			return result;
		}catch (Exception e) {
			result.setStatus(false);
			result.setMessage("获取用户角色错误");
			log.error(e + "获取用户角色错误");
		}
		return result;
	}
	
	/**
	 * 检查用户会话是否过期，如果过期重新分配一个新sessionId
	 * @param sessionId
	 * @return	
	 */
	@Override
	public ResponseForm checkSession(RequestForm requestForm) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public ResponseForm getWxUid(RequestForm requestForm) {
		ResponseForm result = new ResponseForm();
		@SuppressWarnings("unchecked")
		Map<String, Object> paramMap = (Map<String, Object>) requestForm.getData();
		try {
			String storeNo = paramMap.get("storeNo").toString();
			String mobile = paramMap.get("mobile").toString();

			// 从员表中查找
//			Employe queryMap = new Employe();
//			queryMap.setMobile(mobile);
//			queryMap.setStoreNo(storeNo);
//			Employe employe = employeMapper.selectOne(queryMap);

//			Map<String, String> userInfo = new HashMap<String, String>();
//			if (employe != null) {
//				String wxUid = employe.getWxUid();
//				if (null != wxUid && !"".equals(wxUid)) {
//					userInfo.put("storeNo", storeNo);
//					userInfo.put("wxUid", wxUid);
//					result.setData(userInfo);
//					result.setCode("200");
//					result.setMessage("WXUID_VALID");
//					result.setTotal(1);
//					return result;
//				}
//			}
			result.setCode("401");
			result.setMessage("WXUID_NOTEXIST");
			result.setTotal(0);
			return result;
		} catch (Exception e) {
			result.setStatus(false);
			result.setMessage("获取叮店用户Id错误");
			log.error(e + "获取叮店用户Id错误");
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); 
		}
		return result;
	}

	@Transactional
	@Override
	public ResponseForm decodePhoneNumber(RequestForm requestForm) {
		ResponseForm result = new ResponseForm();
		result.setStatus(false);
		result.setCode("0");
		result.setMessage("PARAM_UNKNOWN");
		result.setTotal(0);
		Map<String,Object> paramMap = (Map<String,Object>)requestForm.getData();
		try {
//			String wxUid = paramMap.get("wxUid").toString();
			String sessionId = paramMap.get("wxSid").toString();
			String encryptedData = paramMap.get("encryptedData").toString();
//			String signature = paramMap.get("signature").toString();
			String iv = paramMap.get("iv").toString();
			
			//---此逻辑修改为从redis中获取sessionKey
//			UserSession queryMap = new UserSession();
//			queryMap.setSessionId(sessionId);
//			Map<String,String> map = new HashMap<String,String>();
//			map.put("session_id", sessionId);
			UserSession session = userSessionMapper.getUserSessionBySid(sessionId);
			if(null ==session)
			{
				return result;
			}
			String sessionKey = session.getSessionKey();//
			//解密用户信息
			JSONObject userInfo = WxUserAccessUtil.getUserInfo(encryptedData, sessionKey, iv);
			if(null ==userInfo)
			{
				return result;
			}
			String phoneNumber = userInfo.getString("phoneNumber");		//用户绑定的手机号（国外手机号会有区号）
			String purePhoneNumber = userInfo.getString("purePhoneNumber");//没有区号的手机号
			String countryCode =  userInfo.getString("countryCode");		//	区号
//			Date date = new Date();
//			Timestamp timeStamp = new Timestamp(date.getTime());
			
			//更新微信用户信息:更新用户表
//			WxUser user = new WxUser();
//			user.setWxUid(wxUid);
//			user.setMobile(purePhoneNumber);
//			user.setCreateTime(timeStamp);
//			user.setMobile(mobile);
//			int r = userMapper.updateByPrimaryKeySelective(user);
//			if(r==0 && null!=wxUid)
//				userMapper.insert(user);
			Map<String,String> userSessionInfo = new HashMap<String,String>();
			userSessionInfo.put("phoneNumber", phoneNumber);
			userSessionInfo.put("purePhoneNumber", purePhoneNumber);
			userSessionInfo.put("countryCode", countryCode);
			result.setStatus(true);
			result.setData(userSessionInfo);
			result.setCode("200");
			result.setMessage("SID_VALID");
			result.setTotal(1);
			return result;
		}catch (Exception e) {
			result.setStatus(false);
			result.setMessage("手机号参数转换错误");
			log.error(e + "手机号参数转换错误");
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); 
		}
		return result;
	}
	
	@Transactional
	@Override
	public ResponseForm pullPhone(RequestForm requestForm) {
		ResponseForm result = new ResponseForm();
		result.setStatus(false);
		result.setCode("0");
		result.setMessage("PARAM_UNKNOWN");
		result.setTotal(0);
		Map<String,Object> paramMap = (Map<String,Object>)requestForm.getData();
		try {
			Map<String,String> userSessionInfo = new HashMap<String,String>();
			String wxUid = paramMap.get("wxUid").toString();
			String sessionId = paramMap.get("wxSid").toString();
			String encryptedData = paramMap.get("encryptedData").toString();
//			String signature = paramMap.get("signature").toString();
			String iv = paramMap.get("iv").toString();
			
			//先获从数据库获取用户绑定手机 
			WxUser user = new WxUser();
			user.setWxUid(wxUid);
			user = wxUserMapper.selectOne(user);
			if(user!=null&&StringUtils.isNotBlank(user.getVerifyPhone())) {
				userSessionInfo.put("purePhoneNumber", user.getVerifyPhone());
				result.setData(userSessionInfo);
				result.setStatus(true);
				result.setCode("200");
				result.setMessage("该用户已绑定手机号!");
				return result;
			}
			//---此逻辑修改为从redis中获取sessionKey
//			UserSession queryMap = new UserSession();
//			queryMap.setSessionId(sessionId);
//			Map<String,String> map = new HashMap<String,String>();
//			map.put("session_id", sessionId);
			UserSession session = userSessionMapper.getUserSessionBySid(sessionId);
			if(null ==session)
			{
				return result;
			}
			String sessionKey = session.getSessionKey();//
			//解密用户信息
			JSONObject userInfo = WxUserAccessUtil.getUserInfo(encryptedData, sessionKey, iv);
			if(null ==userInfo)
			{
				return result;
			}
			String phoneNumber = userInfo.getString("phoneNumber");		//用户绑定的手机号（国外手机号会有区号）
			String purePhoneNumber = userInfo.getString("purePhoneNumber");//没有区号的手机号
			String countryCode =  userInfo.getString("countryCode");		//	区号
			if(StringUtils.isBlank(purePhoneNumber)) {
				result.setCode("400");
				result.setMessage("获取手机号失败,session失效或该微信用户无手机号!");
				result.setStatus(false);
				return result;
			}
			Date date = new Date();
			Timestamp timeStamp = new Timestamp(date.getTime());
			//更新微信用户信息:更新用户表
			Integer userId = user.getUserId();
			user = new WxUser();
			user.setUserId(userId);
			user.setWxUid(wxUid);
			user.setVerifyPhone(purePhoneNumber);
			user.setCreateTime(timeStamp);
			int r = wxUserMapper.updateByPrimaryKeySelective(user);
//			if(r==0 && null!=wxUid)
//				userMapper.insert(user);
//			userSessionInfo.put("phoneNumber", phoneNumber);
			userSessionInfo.put("purePhoneNumber", purePhoneNumber);
//			userSessionInfo.put("countryCode", countryCode);
			result.setStatus(true);
			result.setData(userSessionInfo);
			result.setCode("200");
			result.setMessage("拉取手机号授权成功!");
//			result.setTotal(1);
			return result;
		}catch (Exception e) {
			result.setCode("500");
			result.setStatus(false);
			result.setMessage("手机号参数转换错误");
			log.error(e + "手机号参数转换错误");
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); 
		}
		return result;
	}
	
}
